package com.yangcangclub.commons.utils;


import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XmlUtil {

    /**
     * xml字符串转成javabean
     * @param xmlStr
     * @return
     * @throws Exception
     */
    public static Map<String, Object> xmlStrToMap(String xmlStr) {


        Map<String, Object> map = new HashMap<String, Object>();

        try {
            if(StringUtil.isEmpty(xmlStr)) {
                return map;
            }
            //将xml格式的字符串转换成Document对象
            Document doc = DocumentHelper.parseText(xmlStr);
            //获取根节点
            Element root = doc.getRootElement();
            //获取根节点下的所有元素
            List children = root.elements();
            //循环所有子元素
            if(children != null && children.size() > 0) {
                for(int i = 0; i < children.size(); i++) {
                    Element child = (Element)children.get(i);
                    map.put(child.getName(), child.getTextTrim());
                }
            }
        } catch (Throwable t) {
            //ignore
            t.printStackTrace();
        }

        return map;
    }
}
